package repo

import (
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"org.knight/api"
)

const DSN = "root:12345@tcp(localhost:3306)/my_dict?charset=utf8&parseTime=True&loc=Local"

var db *gorm.DB

func init() {

	//newLogger := logger.New(
	//	log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
	//	logger.Config{
	//		SlowThreshold:              time.Second,   // Slow SQL threshold
	//		LogLevel:                   logger.Silent, // Log level
	//		IgnoreRecordNotFoundError: true,           // Ignore ErrRecordNotFound error for logger
	//		Colorful:                  false,          // Disable color
	//	},
	//)

	var err error
	db, err = gorm.Open(mysql.Open(DSN), &gorm.Config{})

	if err != nil {
		panic(err)
	}
}

type DBRepository struct {
}

func (d *DBRepository) DB() *gorm.DB {
	return db
}

func (d *DBRepository) Query(u interface{}) api.QueryResult {

	result := api.QueryResult{Data: &[]interface{}{}}

	log.Printf("query from %s\n", u)

	rst := db.Debug().Table("products").Where(u).Find(result.Data)
	if rst.Error != nil {
		panic(rst.Error.Error())
	}
	result.Count = int(rst.RowsAffected)
	return result

}

func (d *DBRepository) Save(u interface{}) {

	log.Printf("saving data: %s \n", u)

	//if sf, ok := reflect.TypeOf(*u).FieldByName("ID"); ok {
	//	sf.Tag.Get("repo")
	//}

	db.AutoMigrate(u)
	log.Printf("creating data: %s \n", u)

	result := db.Create(u)

	if result.Error != nil {
		panic(result.Error.Error())
	}

	result.Commit()

	//log.Printf("saved data: %v \n", u)

}
